package com.rtx.wms.std.handler.check;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.common.HttpServletRequestUtil;
import com.rtx.edi.platform.field.service.PlFieldMappingService;
import com.rtx.model.dto.edi.EdiInnerRequestDTO;
import com.rtx.wms.std.asn.bean.ApiReceipt;
import com.rtx.wms.std.asn.bean.Receipt;
import com.rtx.wms.std.asn.service.ApiReceiptService;
import com.rtx.wms.std.asn.service.ReceiptService;
import com.rtx.wms.std.so.bean.ApiCancle;
import com.rtx.wms.std.so.bean.ApiOrders;
import com.rtx.wms.std.so.bean.Orders;
import com.rtx.wms.std.so.service.ApiOrdersService;
import com.rtx.wms.std.so.service.OrdersService;


/**
 * 单据编辑前校对
 * @author A
 *
 */
@Component
public class OrderCheckHandler {
	
	Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    PlFieldMappingService plFieldMappingService;
    
    @Autowired
    ApiOrdersService apiOrdersService;
    
    @Autowired
    OrdersService ordersService;
    
    @Autowired
    ApiReceiptService apiReceiptService;
    
    @Autowired
    ReceiptService receiptService;
    
	
    /**
     * 请求报文示例
     * {"whseid":"默认值WMWHSE1","storerkey":"CATECH","externkey":"ERP单ID号","type":"订单类型 "}
     * 响应示例
     * {"whseid":"","storerkey":"catech","externkey":"erp单id号","type":"订单类","code":"","msg":""}
     * @param request
     */
	public String checkOrder(HttpServletRequest request) {
		Map<String,Object> response = new HashMap<>();
		response.put("whseid", "WMWHSE1");
		response.put("storerkey", "CATECH");
		
		String msg = "";
		try {
			String requestStr = HttpServletRequestUtil.getHttpBody(request);
			EdiInnerRequestDTO dto = JSON.parseObject(requestStr, EdiInnerRequestDTO.class);
			
			JSONObject requestData = JSON.parseObject(dto.getTagetjson(), JSONObject.class);
			String type = requestData.getString("type");
			String externkey = requestData.getString("externkey");
			String whseid = requestData.getString("whseid");
			response.put("externkey", externkey);
			
			
			String wemsDatatype = plFieldMappingService.queryWmsDataType("ris_edi", type);
			if("SO".equals(wemsDatatype)) {
				msg = orderCheck(whseid,externkey);
			}else if("ASN".equals(wemsDatatype)) {
				msg = receiptCheck(whseid,externkey);
			}else {
				msg ="单据大类不存在";
			}
		} catch (Exception e) {
			msg = e.getMessage();
			log.error("单据编辑前校对异常",e);
		}

		if(!"ok".equals(msg)) {
			response.put("code", "500");
			response.put("msg", msg);
		}else {
			response.put("code", "200");
			response.put("msg", msg);
		}
		
		return JSON.toJSONString(response);
	}
	
	/**
	 * 返回ok为可以编辑
	 * @param whseid
	 * @param externorderkey
	 * @return
	 */
	public String orderCheck(String whseid, String externorderkey) {
    	LambdaQueryWrapper<ApiOrders> apiordersQuery = Wrappers.lambdaQuery();
    	apiordersQuery.eq(ApiOrders::getExternorderkey, externorderkey);
    	List<ApiOrders> olist = apiOrdersService.selectApiOrdersByWrapper("ris_edi", apiordersQuery,null);
    	
    	String msg ="ok";

    	String P_Status = "";
    	String PS_Status = "";
    	String PF_Status = "";
    	String PC_Status = ""; 
    	if(olist.size() > 0) {
    		for(ApiOrders mo:olist) {
    			if("PS".equals(mo.getEdiflag())) {
    				PS_Status ="true";
    			}
    			if("PF".equals(mo.getEdiflag())) {
    				PF_Status ="true";
    			}
    			if("P".equals(mo.getEdiflag())) {
    				P_Status ="true";
    			}
    			if("PC".equals(mo.getEdiflag())) {
    				PC_Status ="true";
    			} 
    		}
    		if("true".equals(PS_Status)) {
        		LambdaQueryWrapper<Orders> ordersQuery = Wrappers.lambdaQuery();
        		ordersQuery.eq(Orders::getExternorderkey,externorderkey);
        		List<Orders> ordersList = ordersService.selectOrderNotDetailByWrapper(whseid, ordersQuery);
        		Assert.notEmpty(ordersList,"出库单：" + externorderkey + "锁定处理中");
        		int status = Integer.parseInt(ordersList.get(0).getStatus());
        		if(status > 10) {
        			Assert.notEmpty(ordersList,"出库单已开始拣货不可编辑");
        		}
    		}
    	}
    	
    	return msg;
	}
	
	/**
	 * 入库单
	 * @param whseid
	 * @param externreceiptkey
	 * @return
	 */
	public String receiptCheck(String whseid, String externreceiptkey) {
		LambdaQueryWrapper<ApiReceipt> rquery = Wrappers.lambdaQuery();
		rquery.eq(ApiReceipt::getExternreceiptkey, externreceiptkey);
		List<ApiReceipt> rList = apiReceiptService.selectApiReceiptByWrapperNoDetail("ris_edi", rquery);

		String msg ="ok";

		String P_Status = "";
		String PS_Status = "";
		String PF_Status = "";
		String PC_Status = "";

		for(ApiReceipt r:rList) {
			if("PS".equals(r.getEdiflag())) {
				PS_Status ="true";
			}
			if("PF".equals(r.getEdiflag())) {
				PF_Status ="true";
			}
			if("P".equals(r.getEdiflag())) {
				P_Status ="true";
			}
			if("PC".equals(r.getEdiflag())) {
				PC_Status ="true";
			}
		}

		//			if("true".equals(PS_Status)) {
		//		        LambdaQueryWrapper<Receipt> query = Wrappers.lambdaQuery();
		//		        query.eq(Receipt::getExternreceiptkey,externreceiptkey);
		//		        List<Receipt> receiptList = receiptService.selectReceiptByWrapper(whseid, query);
		//		        Assert.notEmpty(receiptList,"入库单：" + externreceiptkey + "不存在");
		//		        int status = Integer.parseInt(receiptList.get(0).getStatus());
		//		        if(status > 4) {
		//		        	msg = "入库单已开始收货不可编辑";
		//		        }
		//	    	}else {
		LambdaQueryWrapper<Receipt> query = Wrappers.lambdaQuery();
		query.eq(Receipt::getExternreceiptkey,externreceiptkey);
		List<Receipt> receiptList = receiptService.selectReceiptByWrapper(whseid, query);
		if(receiptList !=null && receiptList.size()>0) {
			int status = Integer.parseInt(receiptList.get(0).getStatus());
			if(status > 4) {
				msg = "入库单已开始收货不可编辑";
			}
		};
	
		//	    	}

		return msg;
	}
	
}
